package org.jim.server.command.handler;

import org.jim.core.*;
import org.jim.core.exception.ImException;
import org.jim.server.JimServerAPI;
import org.jim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jim.core.packets.Command;
import org.jim.core.packets.ExitGroupNotifyRespBody;
import org.jim.core.packets.OutGroupReqBody;
import org.jim.core.packets.RespBody;
import org.jim.core.packets.User;
import org.jim.core.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;

/**
 * 
 * 版本: [1.0]
 * 功能说明: 加入群组消息cmd命令处理器
 * @author : WChao 创建时间: 2017年9月21日 下午3:33:23
 */
public class DissGroupReqHandler extends AbstractCmdHandler {
	
	private static Logger log = LoggerFactory.getLogger(DissGroupReqHandler.class);
	
	@Override
	public ImPacket handler(ImPacket packet, ImChannelContext channelContext) throws ImException {
		OutGroupReqBody outGroupReqBody = JsonKit.toBean(packet.getBody(), OutGroupReqBody.class);
		String groupId = outGroupReqBody.getGroupId();
		/**  解散群组通知代码  开始  */
		doAfterUnbind(channelContext, outGroupReqBody);
		/**  解散群组通知代码 结束  */
		JimServerAPI.dissGroup(groupId);
	    RespBody respBody = new RespBody(Command.COMMAND_DISS_GROUP_REQ,ImStatus.C10025);
		return ProtocolManager.Converter.respPacket(respBody.setLocalId(outGroupReqBody.getLocalId()), channelContext);
		
	}
	
	public void doAfterUnbind(ImChannelContext imChannelContext, OutGroupReqBody outGroupReqBody) throws ImException {
		//发退出房间通知  COMMAND_EXIT_GROUP_NOTIFY_RESP
		ExitGroupNotifyRespBody exitGroupNotifyRespBody = new ExitGroupNotifyRespBody();
		exitGroupNotifyRespBody.setGroup(outGroupReqBody.getGroupId());
		User clientUser = imChannelContext.getSessionContext().getImClientNode().getUser();
		if(clientUser != null) {
			User notifyUser = User.newBuilder().userId(clientUser.getUserId()).nick(clientUser.getNick()).build();
			exitGroupNotifyRespBody.setUser(notifyUser);
			RespBody respBody = new RespBody(Command.COMMAND_DISS_GROUP_NOTIFY_RESP,exitGroupNotifyRespBody);
			ImPacket imPacket = new ImPacket(Command.COMMAND_DISS_GROUP_NOTIFY_RESP, respBody.setLocalId(outGroupReqBody.getLocalId()).toByte());
			JimServerAPI.sendToGroup(outGroupReqBody.getGroupId(), imPacket);
		}
	}
	
	@Override
	public Command command() {
		return Command.COMMAND_DISS_GROUP_REQ;
	}
}
